package com.gainloop.Listeners;


import java.util.LinkedList;

import com.gainloop.R;
import com.gainloop.Adapters.TagAdapter;
import com.gainloop.Api.Entity.Tag;
import com.gainloop.Utils.HorizontalListView;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class tagButtonListener implements View.OnClickListener{
	
	private AutoCompleteTextView _tagsRow;
	private Context _context;
	private HorizontalListView _addedTagsList;
	
	private TagAdapter _listAdapter;
	private LinkedList<String> _globalTagList;
	
	
	private tagButtonListener(){
		super();
	}
	
	public tagButtonListener(AutoCompleteTextView tagsRow,Context context){
		this();
		_tagsRow =  tagsRow ;
		_context = context;
		
	}
	
	public tagButtonListener(AutoCompleteTextView tagsRow,Context context,HorizontalListView addedTagsList,
			LinkedList<String> globalTagList){
		this();
		_tagsRow =  tagsRow ;
		_context = context;
		_addedTagsList = addedTagsList ;
		
		_listAdapter = (TagAdapter) _addedTagsList.getAdapter();
		if (globalTagList==null){
			globalTagList=new LinkedList<String>();
		}
		else{
			_globalTagList = globalTagList;
		}
	}
	
	
	
	@Override
	public void onClick(View arg0) {
		Log.v("amount of tags in list=",Integer.toString(_globalTagList.size()));
		
		String newTag = _tagsRow.getText().toString();
		int tagLength = newTag.length();
		if(tagLength>Tag.MAX_TAG_LENGTH){
			Toast.makeText(_context, R.string.tag_exceeded_length, Toast.LENGTH_SHORT).show();
			return; 
		}
		if(tagLength==0){
			Toast.makeText(_context, R.string.tag_empty_length, Toast.LENGTH_SHORT).show();
			return; 
		}
		if(containsTag(newTag)){		
			Toast.makeText(_context, R.string.tag_already_exist, Toast.LENGTH_SHORT).show();
			return; 
		}
		addNewTagToView(newTag);
		
		_tagsRow.setText("");
		
		
		
	}
	/**
	 * Checks if the user already entered given Tag.
	 * @param newTag - Tag to check
	 * @return True if user already entered given Tag.
	 */
	private boolean containsTag(String newTag) {
		for(String curTag:_globalTagList){
			if(curTag.compareTo(newTag)==0)
				return true;
		}
		return false; 
	}

	private void addNewTagToView(String newTag) {
		_globalTagList.addLast(newTag);
		_listAdapter.notifyDataSetChanged();
	}

}
